package com.motu.vertx.module.utility.logsdk;

import com.motu.data.UserLoginDevice;
import com.motu.vertx.module.utility.base.BaseServerParam;
import com.motu.vertx.module.utility.base.ServerConfig;
import com.motu.vertx.module.utility.commondata.CommonDataManager;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AdjustManager {
    private static final Logger logger = LoggerFactory.getLogger(AdjustManager.class);

    public static final int ROLE_CREATE = 1;// 用户创角事件
    public static final int ROLE_LOGIN = 2;// 用户登录
    public static final int LOGIN = 3;// 累计登录几天
    public static final int CHARGE = 4;// 充值事件
    public static final int FIRST_CHARGE = 5;// 首充事件
    public static final int COMMON_MONTH_CARD = 6;// 购买普通月卡
    public static final int HIGH_MONTH_CARD = 7;// 购买至尊月卡
    public static final int BOTH_MONTH_CARD = 8;// 双卡同时购买
    public static final int VIP = 9;// 达到某个vip等级
    public static final int LEVEL = 10;// 达到某个等级

	/**
	 * 上报Adjust事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @param eventType 事件类型
	 * @param eventParam 事件参数
	 * @param extParams 扩展参数
	 */
	public static void sendEvent(long userId, UserLoginDevice userLoginDevice, int eventType, int eventParam, Object... extParams) {
        //logger.info("AdjustManager send start userId:{} eventType:{} eventParam:{}", userId, eventType, eventParam);
        if (userLoginDevice == null) {
			//logger.error("AdjustManager send error loginDeviceInfo is null userId:{} eventType:{} eventParam:{}", userId, eventType, eventParam);
			return;
		}
		String ryos = userLoginDevice.getRyos();
		if (!ryos.equalsIgnoreCase("ios") && !ryos.equalsIgnoreCase("android")) {//只判断真机
			//logger.error("AdjustManager send error userId:{} eventType:{} eventParam:{} ryos:{}", userId, eventType, eventParam, ryos);
			return;
		}

		AdjustCode adjustcode = CommonDataManager.getAdjustCode(eventType, eventParam);
		if (adjustcode == null) {
            //logger.error("AdjustManager send error adjustcode is null userId:{} eventType:{} eventParam:{}", userId, eventType, eventParam);
			return;
		}
		AdjustRequestInfo info = new AdjustRequestInfo(userId, userLoginDevice, eventType, eventParam);
		if (extParams.length > 0) {
			double money = (double) extParams[0];
			info.setMoney(money);
		}
		sendLog(adjustcode, info, !ServerConfig.isOnlineServer());
	}

    private static String getEventToken(AdjustCode adjust, AdjustRequestInfo info) {
        if (info.isIosPackage()) {// IOS
            return adjust.getIosCode();
        } else {
            return adjust.getAndroidCode();
        }
    }

	private static void sendLog(AdjustCode adjustcode, AdjustRequestInfo info, boolean isSandbox) {
        ChargePackage cp = CommonDataManager.getChargePackage(ChargePackage.TYPE_ADJUST, info.platform, info.channel);
        if (cp == null || cp.getAdjustCode().isEmpty()) {
            //logger.error("###AdjustManager error cp:" + cp);
            return;
        }
        String appToken = cp.getAdjustCode();
        String eventToken = AdjustManager.getEventToken(adjustcode, info);
        if (eventToken == null) {
            //logger.error("###AdjustManager error eventToken:" + adjustcode.getId());
            return;
        }
        String urlstr = "";//"https://s2s.adjust.com/event?";
        urlstr += "app_token=" + appToken;
        urlstr += "&event_token=" + eventToken;
        urlstr += "&s2s=1";
        urlstr += "&created_at=" + AdjustManager.time();
        if (info.adid != null && !info.adid.isEmpty()) {
            urlstr += "&adid=" + info.adid;
        }
        if (info.isIosPackage()) {// IOS
            if (!(info.idfa.isEmpty() || info.idfa.equals("0"))) {
                urlstr += "&idfa=" + info.idfa;
            }
            urlstr += "&idfv=" + info.idfv;
        } else if (info.isAndroidPackage()) {// 安卓
            if (info.androidid != null && !info.androidid.isEmpty())
                urlstr += "&android_id=" + info.androidid;
            if (info.gps_adid != null && !info.gps_adid.isEmpty())
                urlstr += "&gps_adid=" + info.gps_adid;
        }
        if (info.money > 0) {// 收入事件才需要带这几个参数
            urlstr += "&currency=" + BaseServerParam.LOG_CURRENCY_TYPE;
            urlstr += "&revenue=" + (info.money);
            urlstr += "&environment=" + (isSandbox ? "sandbox" : "production");
        }
        JsonObject callbackParamsJson = new JsonObject();
        callbackParamsJson.put("ta_account_id",""+info.userId);
        if(info.distinctId != null && !info.distinctId.isEmpty()){
            callbackParamsJson.put("ta_distinct_id",info.distinctId);
        }
        urlstr += "&callback_params=" + URLEncoder.encode(callbackParamsJson.toString(), StandardCharsets.UTF_8);
        JsonObject obj = new JsonObject().put("params", urlstr);
        //logger.info("###AdjustManager send succ userid:" + info.userId + " type:" + info.type + " param:" + info.param);
        LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_ADJUST, obj);
    }

	private static String time() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'Z", Locale.ENGLISH);
        String time = format.format(date);
        return URLEncoder.encode(time, StandardCharsets.UTF_8);
    }

}
